<template>
  <div style="display: flex; justify-content: center; align-items: center; width: 100vw;height: 100vh;">
    <div style="width: 1000px; height: 400px; border:1px solid;display: flex;flex-direction: row;">
      <img src="../assets/img/school.ico" style="height: 390px;">
      <el-form style="flex-grow: 1;height: 100%;padding:100px 80px;" :model="loginFormData" :rules="rules"
        ref="loginForm">
        <el-form-item label="账号：" prop="username">
          <el-input v-model="loginFormData.username" id='username'></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="loginFormData.password" id='password'></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 30%;width: 40%;" @click="beginLogin(loginForm)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'

import { useRouter } from 'vue-router'
const router = useRouter()

// userInfo
import { type Employee } from '@/types/database'
import { useUserInfoStore } from '@/stores/userInfo';
const userInfo = useUserInfoStore();

// loginForm
import type { FormInstance } from 'element-plus'
const loginForm = ref<FormInstance>()
const loginFormData = reactive({
  username: '',
  password: ''
})
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度需在6~20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度需在6~20个字符', trigger: 'blur' },
  ],
}
function beginLogin(form: FormInstance | undefined) {
  if (!form) return
  form.validate((valid, fields) => {
    if (valid) {
      if (loginFormData.username == 'test') {
        router.replace('/home/platform')
        userInfo.name = 'test'
        console.log(userInfo)
        return
      } else {
        fetch('/api/admin/employee/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(loginFormData)
        }).then(res => res.json()).then(data => {
          console.log(data)
          if (data.code != 0) {
            userInfo.id = data.data.id
            userInfo.username = loginFormData.username
            userInfo.password = loginFormData.password
            userInfo.name = data.data.name
            sessionStorage.setItem('token', data.data.token)
            sessionStorage.setItem('userId', JSON.stringify(userInfo.id))
            router.replace('/home/platform')
          } else {
            ElMessage({
              message: data.msg,
              type: 'error'
            })
          }
        })
      }


    } else {
      console.log('error submit!', fields)
    }
  })
}


</script>

<style scoped></style>